using Avalonia.BiliBili.Units;
using Avalonia.Controls;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Avalonia.Interactivity;
using Bilibili.Common;
using Bilibili.Model.Parts;
using Bilibili.WebClient.Api;
using PCLUntils.Objects;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Windows
{
    public partial class TopicWindow : WindowBase
    {
        private ActivityClient Client { get; }
        private int PageIndex { get; set; } = 1;
        private ObservableCollection<TopicModel> Topics { get; }
        public TopicWindow()
        {
            InitializeComponent();
            Client = new ActivityClient();
            Topics = new ObservableCollection<TopicModel>();
        }
        protected override void AfterInitializeComponent()
        {
            listView.ItemsSource = Topics;
            listView.ItemClick += ListView_ItemClick;
            listView.ScrollEnd += ListView_ScrollEnd;
            RunOnUiThread(LoadData);
        }
        private void ListView_ScrollEnd(object? sender, RoutedEventArgs e)
        {
            PageIndex++;
            RunOnUiThread(LoadData);
        }
        private void ListView_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.ClickItem is ListBoxItem item && item.Content is TopicModel topic)
                {
                    var url = topic.link;
                    Navigater.OpenWebView(url);
                }
            }
            catch { }
        }
        private async Task LoadData()
        {
            var result = await Client.GetTopic(PageIndex);
            if (result.IsSuccess())
            {
                var m = result.Data;
                if (m.IsNotEmpty() && m.list.Count > 0)
                {
                    m.list.ForEach(x =>
                    {
                        if (x.link.Length != 0)
                        {
                            if (!x.cover.Contains("http:"))
                                x.cover = "http:" + x.cover;
                            Topics.Add(x);
                        }
                    });
                }
            }
            else
                PopupToast.Show(result.Message);
        }
    }
}